#pragma once
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

typedef void (*task_t)();

#define TaskNum 3

task_t task[TaskNum];

void Print()
{
    std::cout << "I am print task!" << std::endl;
}

void DownLoad()
{
    std::cout << "I am download task!" << std::endl;
}

void Flush()
{
    std::cout << "I am flush task!" << std::endl;
}

// 加载任务
void LoadTask()
{
    srand(time(nullptr) ^ getpid()); // 随机数种子
    task[0] = Print;
    task[1] = DownLoad;
    task[2] = Flush;
}

// 执行任务
void ExcuteTask(int number)
{
    if(number < 0 || number > 2) return;
    task[number](); // 调用任务函数
}

// 随机选择一个任务
int SelectTask()
{
    return rand() % TaskNum; // 0~2
}

void work()
{
    while (true)
    {
        int command = 0;
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            // 哪个进程处理的任务
            std::cout << "pid is: " << getpid() << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "subprocess: " << getpid() << " quit" << std::endl;
            // 管道读完后节结束
            break;
        }
    }
}